<template>
  <div class="base-converter">
    <el-row justify="center" class="w-full">
      <el-col :xs="24" :sm="24" :md="20" :lg="18" :xl="16">
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <el-icon color="#ff5722">
                <switch />
              </el-icon>
              <span class="ml-2">进制转换器</span>
            </div>
          </template>

          <!-- 输入区域 -->
          <el-row :gutter="20">
            <el-col :xs="24" :sm="16">
              <el-form-item>
                <el-input v-model="inputValue" :placeholder="`输入${getBaseName(inputBase)}数值`" />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="8">
              <el-select v-model="inputBase" class="w-full">
                <el-option
                  v-for="option in baseOptions"
                  :key="option.value"
                  :label="option.text"
                  :value="option.value"
                />
              </el-select>
            </el-col>
            <!-- 添加转换按钮 -->
            <el-col :span="24" class="mt-4">
              <el-button type="primary" class="w-full" @click="convert">转换</el-button>
            </el-col>
          </el-row>

          <!-- 转换结果 -->
          <el-card class="mt-4">
            <el-scrollbar>
              <div class="result-list">
                <div
                  v-for="base in outputBases"
                  :key="base"
                  class="result-item"
                  :class="{ 'highlight-row': base === inputBase }"
                >
                  <span>{{ getBaseName(base) }}：</span>
                  <div class="result-value">
                    <code>{{ results[base] || '0' }}</code>
                    <el-button link :icon="CopyDocument" @click="copyToClipboard(results[base])" />
                  </div>
                </div>
              </div>
            </el-scrollbar>
          </el-card>

          <!-- 计算历史 -->
          <el-collapse v-model="activeCollapse" class="mt-4">
            <el-collapse-item title="计算历史" name="1">
              <template v-if="history.length">
                <el-scrollbar height="300px">
                  <div class="history-list">
                    <div v-for="(item, index) in history" :key="index" class="history-item">
                      <div>
                        {{ item.input }}
                        ({{ getBaseName(item.base) }})
                      </div>
                      <div class="text-secondary">
                        转换结果：{{ item.result }} ({{ getBaseName(item.targetBase) }})
                      </div>
                      <el-button link :icon="RefreshRight" @click="loadHistory(item)" />
                    </div>
                  </div>
                </el-scrollbar>
                <div class="text-center mt-4">
                  <el-button type="danger" link @click="clearHistory">清空历史</el-button>
                </div>
              </template>
              <el-empty v-else description="暂无历史记录" />
            </el-collapse-item>
          </el-collapse>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { Switch, CopyDocument, RefreshRight } from '@element-plus/icons-vue';

const inputValue = ref('');
const inputBase = ref(10);
const results = ref({});
const history = ref([]);

const baseOptions = [
  {
    text: '二进制',
    value: 2
  },
  {
    text: '八进制',
    value: 8
  },
  {
    text: '十进制',
    value: 10
  },
  {
    text: '十六进制',
    value: 16
  }
];

const outputBases = [2, 8, 10, 16];

const validateInput = value => {
  if (!value) return true;

  const patterns = {
    2: /^[01]+$/,
    8: /^[0-7]+$/,
    10: /^\d+$/,
    16: /^[0-9A-Fa-f]+$/
  };

  return patterns[inputBase.value].test(value);
};

const convert = () => {
  if (!inputValue.value || !validateInput(inputValue.value)) {
    results.value = {};
    return;
  }

  try {
    // 先转换为十进制
    const decimalValue = parseInt(inputValue.value, inputBase.value);

    // 转换为其他进制
    results.value = {
      2: decimalValue.toString(2),
      8: decimalValue.toString(8),
      10: decimalValue.toString(10),
      16: decimalValue.toString(16).toUpperCase()
    };

    // 保存到历史记录
    saveToHistory(decimalValue);
  } catch (error) {
    ElMessage.error('转换失败，请检查输入');
  }
};

const getBaseName = base => {
  const names = {
    2: '二进制',
    8: '八进制',
    10: '十进制',
    16: '十六进制'
  };
  return names[base];
};

const copyToClipboard = async text => {
  try {
    await navigator.clipboard.writeText(text);
    ElMessage.success('已复制到剪贴板');
  } catch (error) {
    ElMessage.error('复制失败');
  }
};

const saveToHistory = decimalValue => {
  const historyItem = {
    input: inputValue.value,
    base: inputBase.value,
    decimal: decimalValue,
    results: { ...results.value }, // 保存所有进制的结果
    timestamp: new Date().toISOString()
  };

  history.value.unshift(historyItem);
  if (history.value.length > 10) {
    history.value.pop();
  }

  localStorage.setItem('baseConverterHistory', JSON.stringify(history.value));
};

const loadHistory = item => {
  inputValue.value = item.input;
  inputBase.value = item.base;
  results.value = { ...item.results }; // 直接加载保存的所有结果
};

const clearHistory = () => {
  history.value = [];
  localStorage.removeItem('baseConverterHistory');
  ElMessage.success('历史记录已清空');
};

// 添加 collapse 激活项控制
const activeCollapse = ref(['1']); // 默认展开第一项

onMounted(() => {
  // 从本地存储加载历史记录
  const savedHistory = localStorage.getItem('baseConverterHistory');
  if (savedHistory) {
    history.value = JSON.parse(savedHistory);
  }
});
</script>

<style scoped>
.base-converter {
  width: 100%;
  padding: 20px;
}

:deep(.el-row) {
  width: 100%;
  margin: 0 !important;
}

.box-card {
  width: 100%;
}

.card-header {
  display: flex;
  align-items: center;
  font-size: 1.2em;
}

.ml-2 {
  margin-left: 0.5rem;
}

.mt-4 {
  margin-top: 1rem;
}

.w-full {
  width: 100%;
}

.result-list,
.history-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.result-item,
.history-item {
  padding: 12px;
  border-radius: 4px;
  background-color: var(--el-fill-color-blank);
  transition: background-color 0.2s;
}

.result-item:hover,
.history-item:hover {
  background-color: var(--el-fill-color-light);
}

.highlight-row {
  background-color: var(--el-fill-color-light);
}

.result-value {
  display: flex;
  align-items: center;
  gap: 8px;
}

code {
  font-family: 'Fira Code', monospace;
  background-color: var(--el-fill-color-light);
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 0.9em;
}

.text-secondary {
  color: var(--el-text-color-secondary);
  font-size: 0.9em;
}

.text-center {
  text-align: center;
}

.result-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.result-list-item {
  padding: 12px;
  border-radius: 4px;
  background-color: var(--el-fill-color-blank);
}

.history-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.history-list-item {
  padding: 12px;
  border-radius: 4px;
  background-color: var(--el-fill-color-blank);
}

.history-content {
  flex: 1;
}

.history-input {
  font-weight: 500;
  margin-bottom: 8px;
}

.history-results {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
  gap: 8px;
}
</style>
